<?php


namespace app\common\controller\xilujob;


use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\xilujob\XilujobUser;
use think\Config;
use think\Hook;
use think\Route;
use function fast\array_get;

class XilujobApi extends Api {

    protected $noNeedRight = '*';
    protected $cityId;

    /**
     * 定义action的用户组权限, 若action未在此定义，意味着所有用户组都可用
     * @var string|array
     */
    protected $restrictedActions = [
        //example
        // '*' => [2,],
        // '$actionName' => [1,2,3,4]  数组里写允许调用的用户组id
    ];
    //默认城市
    const DEFAULT_CITY_ID = 802; //上海

    protected function _initialize()
    {
        if (Config::get('url_domain_deploy')) {
            $domain = Route::rules('domain');
            if (isset($domain['api'])) {
                if (isset($_SERVER['HTTP_ORIGIN'])) {
                    header("Access-Control-Allow-Origin: " . $this->request->server('HTTP_ORIGIN'));
                    header('Access-Control-Allow-Credentials: true');
                    header('Access-Control-Max-Age: 86400');
                }
                if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
                    }
                    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                    }
                }
            }
        }

        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $this->cityId = $this->request->header('cityid')===null ? self::DEFAULT_CITY_ID : $this->request->header('cityid');

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), null, 401);
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'));
                }
            }
            // 判断action是否有限制用户组使用
            if(isset($this->restrictedActions['*']) || isset($this->restrictedActions[$actionname])) {
                $user = $this->auth->getUser();
                $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
                $allowedGroups = array_get($this->restrictedActions, $actionname, []) ? : array_get($this->restrictedActions,'*', []);
                if($allowedGroups!=='*' && !in_array($xilujobuser->group_id, $allowedGroups)) {
                    $targetGroupId = $allowedGroups[0];
                    $tip = $targetGroupId == XilujobUser::GROUP_MEMBER ? '个人用户':'企业用户';
                    $this->error(__("请切换到{$tip}身份使用"),null, 403);
                }
            }
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

//        $user = $this->auth->getUser();
        //
//        if($user) {
//            $now = time();
//            $user->save(['actiontime'=>$now]);
//            //每小时+1的活跃度
//            if($user->group_id==User::GROUP_MEMBER) {
//                $logType = 1;
//            }else if ($user->group_id==User::GROUP_COMPANY || $user->group_id==User::GROUP_LABOUR){
//                $logType = 2;
//            }else if($user->group_id==User::GROUP_TRAINER) {
//                $logType = 3;
//            }else {
//                $logType = -1;
//            }
//            $log = UserActiveLog::where('user_id',$user->id)->where('type', $logType)->order('active_time','desc')->find();
//            $activeTime = $log ? $log->active_time : null;
//            if(!$activeTime || $activeTime<$now-3600) {
//                UserActiveLog::create(['user_id'=>$user->id,'type'=>$logType,'active_time'=>$now]);
//            }
//        }

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

}